package cn.stronglink.asset.message.mq.dam.handle;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import cn.stronglink.asset.message.mq.dam.entity.IScreenCommandFactory;
import cn.stronglink.asset.message.mq.dam.entity.ScreenCommandEntity;
import cn.stronglink.asset.message.mq.dam.entity.dacai.UpdateArrayTextCommandFactory;
import cn.stronglink.asset.message.mq.dam.message.MQMessageOfDAM;
import cn.stronglink.asset.message.mq.topic.ReaderInfoSender;
import cn.stronglink.asset.module.dam.service.DamService;
import cn.stronglink.asset.module.dam.service.IDamService;
import cn.stronglink.suite.core.util.ByteUtil;
import cn.stronglink.suite.core.util.ContextUtils;

public class AssetBindRfidPageHandle extends AbstractReturnExceptionHandle{
	
	protected final static String TOPIC_NAME = "serviceToDam";
	protected final static String ACTION_CODE = "screenRequest";
	protected final static String SEND_ACTION_CODE= "screenCommand";
	protected IDamService damService =(DamService)ContextUtils.getBean("sensorService");
	private ReaderInfoSender topicSender = (ReaderInfoSender) ContextUtils.getBean("readerInfoSender");
	private final static short DIALOG_ID = 1;
	private final static short DIALOG_SCREEN_ID = 12;
	private long lastReceiveTime =0;
	private final static int MAX_INTERVAL_TIME = 3000;
	private boolean isReceiveAssetIdCommand=false;
	private boolean isReceiveRfidCommand=false;
	private boolean isReceiveStartUCommand = false;
	private boolean isReceiveBtnCommand = false;
	private String rfid = "";
	private String assetId = "";
	private int startU = 0;
	@Override
	public boolean isHandle(MQMessageOfDAM msg) {
		ScreenCommandEntity entity = (ScreenCommandEntity) msg.getAwsPostdata();
		if(entity!=null) {
			int controlId = hexStringToControlId(entity.getCommand());
			if(entity.getCommand().indexOf("EEB111000A")==0 
					&& ((controlId>0 && controlId<110)||(controlId>200 && controlId<223))) {
				return true;
			}
		}
		return false;
	}

	@Override
	protected void handleMessage(MQMessageOfDAM msg) {
		ScreenCommandEntity entity = null; 
		Map<Short, String> map = null;
		
		try {
			if(System.currentTimeMillis()-lastReceiveTime>MAX_INTERVAL_TIME) {
				this.clearData();
			}
			entity = (ScreenCommandEntity) msg.getAwsPostdata();
			map = new HashMap<>();
			if(entity!=null) {
				int controlId = hexStringToControlId(entity.getCommand());
				if(entity.getCommand().indexOf("EEB111000A")==0
						&& ((controlId>0 && controlId<110)||(controlId>200 && controlId<223))) {
					if(!this.isReceiveAssetIdCommand&&controlId>0 && controlId<110) {
						this.isReceiveAssetIdCommand = true;
						String assetIdCommandStr = entity.getCommand().substring(16, entity.getCommand().length()-2);
						if(!assetIdCommandStr.equals("20")) {
							this.assetId = new String(ByteUtil.hexStringToBytes(assetIdCommandStr)).trim();
						}
					}else if(!this.isReceiveRfidCommand&&controlId>0 && controlId<110) {
						this.isReceiveRfidCommand = true;
						String rfidCommandStr = entity.getCommand().substring(16, entity.getCommand().length()-2);
						if(!rfidCommandStr.equals("20")) {
							this.rfid = new String(ByteUtil.hexStringToBytes(rfidCommandStr)).trim();
						}
					}else if(!this.isReceiveStartUCommand&&controlId>0 && controlId<110){
						this.isReceiveStartUCommand = true;
						String startUCommandStr = entity.getCommand().substring(16, entity.getCommand().length()-2);
						if(!startUCommandStr.equals("20")) {
							this.startU = Integer.parseInt(new String(ByteUtil.hexStringToBytes(startUCommandStr)).trim());
						}
					}else if(!this.isReceiveBtnCommand&&controlId>200 && controlId<223) {
						this.isReceiveBtnCommand = true;
					}
				}
			}
			
			if(this.isReceiveAssetIdCommand && this.isReceiveRfidCommand && this.isReceiveStartUCommand 
					&& this.isReceiveBtnCommand) {
				// 绑定
				System.out.println("assetId:"+assetId+"--------"+"rfid:"+rfid+"----"+"startU:"+startU);
				
				if(assetId.equals("")||assetId.isEmpty()) {
					// 未找到该机柜
					map.put(DIALOG_ID, "资产id不能为空!");
				}else if(rfid.equals("")||rfid.isEmpty()) {
					map.put(DIALOG_ID, "rfid不能为空!");
				}else if(startU==0) {
					map.put(DIALOG_ID, "起始u位不能为空!");
				}else {
					
					damService.updateAssetRfid(assetId,rfid);
					damService.updateAssetUInfo(assetId,startU);
					map.put(DIALOG_ID, startU+"u rfid为["+rfid+"]的设备绑定成功!");
				}
				sendCommandToScreen(entity.getRackConverCode(),map);
				map.clear();
				this.clearData();
			}
			this.lastReceiveTime = System.currentTimeMillis();
		}catch (Exception e) {
			e.printStackTrace();
			map.put(DIALOG_ID, e.getMessage()+"");
			try {
				sendCommandToScreen(entity.getRackConverCode(),map);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

	private void sendCommandToScreen(String rackConverCode,Map<Short,String> map) throws Exception {
		IScreenCommandFactory rackScreenCommandFactroy = new UpdateArrayTextCommandFactory(rackConverCode, DIALOG_SCREEN_ID, map);
		ScreenCommandEntity sc =  rackScreenCommandFactroy.createScreenCommand();
		
		MQMessageOfDAM message = new MQMessageOfDAM();
		message.setActioncode(SEND_ACTION_CODE);
		message.setAwsPostdata(sc);
		message.setTimestamp(System.currentTimeMillis());
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME,json);
		logger.info("topic:{}  发送命令:{}",TOPIC_NAME,json);
		
		
		ScreenCommandEntity changeScreen =  rackScreenCommandFactroy.changeScreenCommand();
		
		MQMessageOfDAM msg = new MQMessageOfDAM();
		msg.setActioncode(SEND_ACTION_CODE);
		msg.setAwsPostdata(changeScreen);
		msg.setTimestamp(System.currentTimeMillis());
		
		String changeScreenJson = JSON.toJSONString(msg);
		topicSender.send(TOPIC_NAME,changeScreenJson);
		logger.info("topic:{}  发送命令:{}",TOPIC_NAME,changeScreenJson);
		
	}
	
	private void clearData() {
		this.isReceiveAssetIdCommand = false;
		this.isReceiveRfidCommand =false;
		this.isReceiveStartUCommand = false;
		this.isReceiveBtnCommand = false;
		this.assetId = "";
		this.rfid = "";
		this.startU = 0;
	}
	
	private int hexStringToControlId(String command) {
		int id = 0;
		if(command.length()>18) {
			id = Integer.parseInt(command.substring(11, 14),16);
		}
		return id;
	}
}
